/**
 * MIT License
 * <p>
 * Copyright (c) 2017-2018 nuls.io
 * <p>
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * <p>
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * <p>
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package io.nuls.klines.scheduled;

import io.nuls.core.parse.JSONUtils;
import io.nuls.klines.entity.ExchangeInfoEntity;
import io.nuls.klines.entity.KlineModel;
import io.nuls.klines.entity.SyncInfoEntity;
import io.nuls.klines.service.AppService;
import io.nuls.klines.util.AppUtil;
import io.nuls.klines.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import io.nuls.klines.context.ServerContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 同步K线定时任务
 *
 * @author: PierreLuo
 * @date: 2020-04-15
 */
@Component
@Slf4j
public class SyncKlinesScheduled {

    private String klineUrl1 = "api/v3/klines?symbol=";

    private String klineUrl2 = "&interval=1d&limit=21";

    @Resource
    private AppService appService;

    private SyncError syncError = new SyncError();

    /**
     * 每天早上8点10分，从币安获取所有xxx/USDT交易对前22天的K线数据，并做分析，
     * 将满足筛选条件的数据，存储到Kline表里
     * 筛选条件：
     * 前一天k线收盘价大于开盘价，且开盘价 ≤ ma5均线 ≤ 收盘价，且开盘价 ≤ ma10均线 ≤ 收盘价，且开盘价 ≤ ma20均线 ≤ 收盘价
     */
    //@Scheduled(cron = "0 10 8 * * *")
    @Scheduled(cron = "0/30 * * * * *")
    public void execute() {
        if (syncError.isError()) {
            log.error("同步交易对K线数据，新增前一天的交易K线，发生错误");
            return;
        }
        log.info("同步交易对K线数据");
        try {
            //获取今天的日期
            String today = TimeUtil.dateFormat(System.currentTimeMillis());
            //获取今天的同步信息
            SyncInfoEntity syncInfo = appService.getTodaySyncInfo(today);
            //如果今日已同步完成，不再继续同步
            if (syncInfo != null && syncInfo.getStatus() == 1) {
                return;
            }
            //为空，说明是今日第一次同步，先存储到数据库
            if (syncInfo == null) {
                syncInfo = new SyncInfoEntity(today);
                syncInfo = appService.saveSyncInfo(syncInfo);
            } else {
                //检查是否所有交易对已同步完成，已同步完成则不在同步
                long count = appService.existUnSyncExchange(today);
                if (count == 0) {
                    syncInfo.setStatus(1);
                    appService.updateSyncInfo(syncInfo);
                    return;
                }
            }

            //获取数据库存储的所有xxx/USDT交易对
            List<ExchangeInfoEntity> exchangeList = appService.getAllExchangeList();
            for (ExchangeInfoEntity exchange : exchangeList) {
                //首先判断交易对是否当天已同步过，已同步过的不再处理
                if (today.equals(exchange.getDay())) {
                    continue;
                }
                exchange.setDay(today);
                //从币安获取交易对最近22天的数据
                String info = AppUtil.getWithProxy(ServerContext.binanceApiHost + klineUrl1 + exchange.getSymbol() + klineUrl2, null, StandardCharsets.UTF_8.name());
                LinkedList<KlineModel> modelList = transKlineModel(info);

                appService.saveKlines(exchange, modelList);

                //这里睡2秒，是为了防止频繁的调用币安接口被封IP，如果2秒不够的话，可以改大
                Thread.sleep(2000);
            }

        } catch (Exception e) {
            log.error("sync Kline error ", e);
            syncError.setError();
        }
    }

    /**
     * 将数据转换成model对象
     * 注意这里获取到K线图数据，转换成klineModel对象后，反序存放到List中
     * 方便后面的逻辑操作
     *
     * @param info
     * @return
     */
    private LinkedList<KlineModel> transKlineModel(String info) throws IOException {
        LinkedList<KlineModel> modelList = new LinkedList<>();
        List<ArrayList> list = JSONUtils.json2pojo(info, ArrayList.class);
        for (int i = 0; i < list.size(); i++) {
            List kline = list.get(i);
            String openTime = TimeUtil.dateFormat(Long.parseLong(kline.get(0).toString()));
            BigDecimal openPrice = new BigDecimal(kline.get(1).toString());
            String endTime = TimeUtil.dateFormat(Long.parseLong(kline.get(6).toString()));
            BigDecimal endPrice = new BigDecimal(kline.get(4).toString());

            KlineModel model = new KlineModel(openTime, openPrice, endTime, endPrice);
            modelList.addFirst(model);
        }
        return modelList;
    }

}
